from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from .models import Student, Teacher

@receiver(post_save, sender=Student)
def create_user_for_student(sender, instance, created, **kwargs):
    if created and not instance.user:
        # 创建用户账号
        username = instance.student_id
        user = User.objects.create_user(
            username=username,
            password=username,  # 初始密码设置为学号
            email=instance.email,
            first_name=instance.name
        )
        # 关联学生和用户
        instance.user = user
        instance.save()

@receiver(post_save, sender=Teacher)
def create_user_for_teacher(sender, instance, created, **kwargs):
    if created and not instance.user:
        # 创建用户账号
        username = instance.teacher_id
        user = User.objects.create_user(
            username=username,
            password=username,  # 初始密码设置为工号
            email=instance.email,
            first_name=instance.name,
            is_staff=True  # 教师默认设置为工作人员
        )
        # 关联教师和用户
        instance.user = user
        instance.save() 